package com.nice.demo;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nice.demo.test.DrawType;
import com.nice.demo.test.MyHandWritingView;
import com.nice.demo.test.ZuotiHandNestedScrollView;
import com.nice.demo.test.ZuotiHandScrollView;
import com.nice.demo.test.bean.PathInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Desc:
 * Company: XueHai
 *
 * @author yuyejiang
 */
public class HandWritingActivity extends AppCompatActivity implements View.OnClickListener {
    private String dataStr = "<html><body>" +
            "<style>img{ width:100% !important;}</style>"
            + "<img src=\"https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/dd9d1d686cdc814db9653b254e00402e_259_194.jpg\" alt=\"\" /> \r" +
            "<img src=\"https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/dd9d1d686cdc814db9653b254e00402e_259_194.jpg\" alt=\"\" /> \r" +
            "<p style=\"text-align:right;\">\r\t品类定位的思考\r</p>\r" +
            "<h3>\r\t<strong><span style=\"color:#00D5FF;\">品类定</span></strong>\n" +
            "<h3>\r\t" +
            "<a href='javascript:mobile.testToast(\"点击\")'>点击我跳回APP</a>"
            + "</body></html>";
    private WebView mWebView;

    public static final String STROKE_PARENT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/Android/data/com.nice.demo/纳思-云作业/";
    public static final String STROKE_FILE_NAME = "strokes.txt";
    public static final String STROKE_FILE_PATH = STROKE_PARENT_PATH + STROKE_FILE_NAME;
    private Spinner mRubberOrWriteSp;
    private Spinner mColorSp;
    private Spinner mDrawTypeSp;
    private Button mAddBtn;
    private Button mSubtractBtn;
    private Button mSaveStrokesBtn;
    private Button mRestoreBtn;
    private Button mDeleteBtn;
    private Button mClearBtn;
    private MyHandWritingView mHandWritingView;
    private LinearLayout mRootLl;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handwriting);
        initView();
        initDataAndSpinner();
    }

    private void initView() {
        mRubberOrWriteSp = (Spinner) findViewById(R.id.rubber_or_write_sp);
        mColorSp = (Spinner) findViewById(R.id.color_sp);
        mDrawTypeSp = (Spinner) findViewById(R.id.draw_type_sp);
        mAddBtn = (Button) findViewById(R.id.add_btn);
        mSubtractBtn = (Button) findViewById(R.id.subtract_btn);
        mSaveStrokesBtn = (Button) findViewById(R.id.save_strokes_btn);
        mRestoreBtn = (Button) findViewById(R.id.restore_btn);
        mDeleteBtn = (Button) findViewById(R.id.delete_btn);
        mClearBtn = (Button) findViewById(R.id.clear_btn);
        mHandWritingView = findViewById(R.id.hand_writing_view);
        mRootLl = (LinearLayout) findViewById(R.id.root_ll);

        mAddBtn.setOnClickListener(this);
        mSubtractBtn.setOnClickListener(this);
        mSaveStrokesBtn.setOnClickListener(this);
        mRestoreBtn.setOnClickListener(this);
        mDeleteBtn.setOnClickListener(this);
        mClearBtn.setOnClickListener(this);

        mHandWritingView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int toolType = event.getToolType(0);
                if (toolType == MotionEvent.TOOL_TYPE_FINGER) {
                    //手指触摸
                    return false;
                } else if (toolType == MotionEvent.TOOL_TYPE_STYLUS) {
                    //手写笔触摸
                    return false;
                } else {
                    //其他
                    return false;
                }
            }
        });
        initWebView();

    }

    private void initDataAndSpinner() {
        List<String> rubberOrWriteList = new ArrayList<>();
        rubberOrWriteList.add("手写");
        rubberOrWriteList.add("橡皮");

        List<String> colorList = new ArrayList<>();
        colorList.add("蓝色");
        colorList.add("红色");

        List<String> drawTypeList = new ArrayList<>();
        drawTypeList.add("曲线");
        drawTypeList.add("点曲线");
        drawTypeList.add("直线");
        drawTypeList.add("点直线");
        drawTypeList.add("箭头");
        drawTypeList.add("直角三角形");
        drawTypeList.add("矩形");
        drawTypeList.add("梯形");
        drawTypeList.add("椭圆");
        drawTypeList.add("坐标系");
        drawTypeList.add("数轴");
        drawTypeList.add("等腰三角形");
        drawTypeList.add("菱形");
        drawTypeList.add("平行四边形");
        ArrayAdapter<String> rubberOrWriteAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, rubberOrWriteList);
        ArrayAdapter<String> colorAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, colorList);
        ArrayAdapter<String> drawTypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, drawTypeList);

        mRubberOrWriteSp.setAdapter(rubberOrWriteAdapter);
        mRubberOrWriteSp.setSelection(0);
        mRubberOrWriteSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mHandWritingView == null) {
                    return;
                }
                switch (position) {
                    case 0: // 手写
                        mHandWritingView.setToWriting();
                        break;
                    case 1: // 橡皮
                        mHandWritingView.setToRubber();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mColorSp.setAdapter(colorAdapter);
        mColorSp.setSelection(0);
        mColorSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mHandWritingView == null) {
                    return;
                }
                switch (position) {
                    case 0: // 蓝色
                        mHandWritingView.setPenColor(Color.BLUE);
                        mHandWritingView.setGeometryPaintColor(Color.BLUE);
                        break;
                    case 1: // 红色
                        mHandWritingView.setPenColor(Color.RED);
                        mHandWritingView.setGeometryPaintColor(Color.RED);
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mDrawTypeSp.setAdapter(drawTypeAdapter);
        mDrawTypeSp.setSelection(0);
        mDrawTypeSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mHandWritingView == null) {
                    return;
                }
                switch (position) {
                    case 0: // 曲线
                        mHandWritingView.setDrawType(DrawType.CURVE);
                        break;
                    case 1: // 点曲线
                        mHandWritingView.setDrawType(DrawType.DASH);
                        break;
                    case 2: // 直线
                        mHandWritingView.setDrawType(DrawType.LINE);
                        break;
                    case 3: // 点直线
                        mHandWritingView.setDrawType(DrawType.DASHLINE);
                        break;
                    case 4: // 箭头
                        mHandWritingView.setDrawType(DrawType.ARROW);
                        break;
                    case 5: // 三角形
                        mHandWritingView.setDrawType(DrawType.TRIANGLE);
                        break;
                    case 6: // 矩形
                        mHandWritingView.setDrawType(DrawType.RECTANGLE);
                        break;
                    case 7: // 梯形
                        mHandWritingView.setDrawType(DrawType.TRAPEZIUM);
                        break;
                    case 8: // 椭圆
                        mHandWritingView.setDrawType(DrawType.OVAL);
                        break;
                    case 9: // 坐标系
                        mHandWritingView.setDrawType(DrawType.COORDINATE);
                        break;
                    case 10: // 数轴
                        mHandWritingView.setDrawType(DrawType.NUMBER_AXIS);
                        break;
                    case 11: // 等腰三角形
                        mHandWritingView.setDrawType(DrawType.ISOSCELESTRIANGLE);
                        break;
                    case 12: // 菱形
                        mHandWritingView.setDrawType(DrawType.RHOMBUS);
                        break;
                    case 13: // 平行四边形
                        mHandWritingView.setDrawType(DrawType.PARALLELOGRAM);
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    public void onClick(View view) {
        if (mHandWritingView == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.add_btn: // 增大手写区
                addWriteArea(mHandWritingView);
                break;
            case R.id.subtract_btn: // 减小手写区
                subtractWriteArea(mHandWritingView);
                break;
            case R.id.save_strokes_btn: // 保存笔迹
                Log.e("jc", STROKE_FILE_PATH);
                //800,1484,402,316&1.0@0#-16776961#389,316,0.40946028;392,314,0.2915797;395,312,0.28639212;398,311,0.29681566;402,309,0.3028804;402,309,0.24147438#389,309,402,316
                //800,1484,432,242&1.0@0#-16776961#432,239,0.45945674;432,239,0.3602379#432,239,432,239=0#-16776961#429,242,0.4189588;431,241,0.5065298#429,241,431,242
                //800,1484,375,703&1.0@0#-16776961#372,703,0.37945157;375,698,0.52423525;375,698,0.47096652#372,698,375,703
                FileOutputStream fos = null;
                try {
                    File file = new File(STROKE_PARENT_PATH);
                    if (!file.exists()) {
                        boolean mkdirs = file.mkdirs();
                        Log.e("jc", "mkdirs=" + mkdirs);
                        if (!mkdirs) {
                            return;
                        }
                    }

                    String strokes = mHandWritingView.getStrokes();
                    if (TextUtils.isEmpty(strokes)) {
                        Toast.makeText(this, "笔迹内容为空!没有需要保存的笔迹!", Toast.LENGTH_SHORT).show();
//                        CustomToastUtil.showInfoToast("笔迹内容为空!没有需要保存的笔迹!");
                        return;
                    }

                    fos = new FileOutputStream(STROKE_FILE_PATH);
                    fos.write(strokes.getBytes()); //写入本地
                    Toast.makeText(this, "笔迹保存成功!", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "IOException", Toast.LENGTH_SHORT).show();
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case R.id.restore_btn: // 还原笔迹
             //   new Thread(new UIUpdateThread()).start();
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(STROKE_FILE_PATH);
                    byte[] bytes = new byte[8192];
                    int len;
                    StringBuilder sb = new StringBuilder();
                    while ((len = fis.read(bytes)) != -1) {
                        sb.append(new String(bytes, 0, len));
                    }
                    String strokes = sb.toString();
//                    某些设备获取event.getPressure()时得到一个野值导致笔迹压力出现一个异常大或者异常小的值，出现某部分手写区块变成了色块

                    if (TextUtils.isEmpty(strokes)) {
                        Toast.makeText(this, "没有可以还原的笔迹!", Toast.LENGTH_SHORT).show();
//                        CustomToastUtil.showErrorToast("没有可以还原的笔迹!");
                        return;
                    }
                  SparseArray<PathInfo> infoSparseArray=  new Gson().fromJson(strokes, new TypeToken<SparseArray<PathInfo>>(){}.getType());
                    if (mHandWritingView != null) {
                        mHandWritingView.clear();
                        mHandWritingView.restoreToImage(infoSparseArray);
                    }
                } catch (IOException e) {
                    Toast.makeText(this, "笔迹文件还没有保存!无法复原笔迹!", Toast.LENGTH_SHORT).show();
//                    CustomToastUtil.showErrorToast("笔迹文件还没有保存!无法复原笔迹!");
                    e.printStackTrace();
                }  finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.delete_btn: // 删除笔迹文件
                File file = new File(STROKE_FILE_PATH);
                if (file.exists() && file.isFile()) {
                    if (file.delete()) {
                        Toast.makeText(this, "笔迹文件删除成功!", Toast.LENGTH_SHORT).show();
//                        CustomToastUtil.showSuccessToast("笔迹文件删除成功!");
                    } else {
                        Toast.makeText(this, "笔迹文件删除失败!", Toast.LENGTH_SHORT).show();
//                        CustomToastUtil.showErrorToast("笔迹文件删除失败!");
                    }
                } else {
//                    CustomToastUtil.showErrorToast("笔迹文件不存在!");
                }
                break;
            case R.id.clear_btn:
                if (mHandWritingView != null) {
                    mHandWritingView.clear();
                }
                break;
        }
    }


    class UIUpdateThread implements Runnable {
        long time = 40000;
        long sleeptime = 100;

        public void run() {
            try {
                while (time < 200000) {
                    Thread.sleep(sleeptime);
                    //mView.updateIndex(time);//.index = mLyric.getNowSentenceIndex(time);
                    // Log.v("UIThread", mView.index + ":" + time);
                    time += sleeptime;
                    mHandler.post(mUpdateResults);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    Handler mHandler = new Handler();
    Runnable mUpdateResults = new Runnable() {
        public void run() {
            //mView.invalidate(); // 更新视图
        }
    };


    /**
     * 第一等级
     */
    int LEVEL_ONE = 1;

    /**
     * 第二等级
     */
    int LEVEL_TWO = 2;
    /**
     * 第三等级
     */
    int LEVEL_THREE = 3;
    int mDefHeight = 500;

    /**
     * 增加手写区域
     */
    private void addWriteArea(MyHandWritingView handWritingView) {
        int currentHeightLevel = getCurrentHeightLevel(handWritingView);
        if (currentHeightLevel == LEVEL_THREE) {
            Toast.makeText(this, "已达最大高度!", Toast.LENGTH_SHORT).show();
            return;
        }

        currentHeightLevel++;
        if (currentHeightLevel > LEVEL_THREE) {
            currentHeightLevel = LEVEL_THREE;
        }
        resetHandWritingHeight(currentHeightLevel, handWritingView);
    }

    /**
     * 减少手写区域
     */
    private void subtractWriteArea(MyHandWritingView handWritingView) {
        int currentHeightLevel = getCurrentHeightLevel(handWritingView);
        if (currentHeightLevel == LEVEL_ONE) {
            Toast.makeText(this, "已达最小高度!", Toast.LENGTH_SHORT).show();
            return;
        }

        currentHeightLevel--;
        if (currentHeightLevel < LEVEL_ONE) {
            currentHeightLevel = LEVEL_ONE;
        }
        resetHandWritingHeight(currentHeightLevel, handWritingView);
    }

    /**
     * 重置手写控件高度
     *
     * @param level           高度等级
     * @param handWritingView 手写控件
     */
    private void resetHandWritingHeight(int level, MyHandWritingView handWritingView){
        if (handWritingView != null) {
            boolean isRubber = handWritingView.isRubber();
            DrawType drawType = handWritingView.getDrawType();

            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) handWritingView.getLayoutParams();
            layoutParams.height = mDefHeight * level;
            handWritingView.setLayoutParams(layoutParams);

            //---------现在增减手写控件高度的时候，手写控件会还原笔迹--------------------------
            //还原笔迹
            try {
                String strokes = handWritingView.getStrokes();
                JSONObject jsonObject=new JSONObject(strokes);
                Object list=  jsonObject.get("list");
                SparseArray<PathInfo> pathInfoList=(SparseArray<PathInfo>) list;
                handWritingView.restoreToImage(pathInfoList);
            }catch (Exception e){
                e.printStackTrace();
            }
            /*f (!TextUtils.isEmpty(strokes)) {


            }*/

            //还原橡皮类型，必须放在restoreToImage(stokes)方法之后，因为restoreToImage(stokes)内部会重置成笔迹
            if (isRubber) {
                handWritingView.setToRubber();
            }
            //还原笔迹类型，必须放在restoreToImage(stokes)方法之后
            if (drawType != DrawType.CURVE) {
                handWritingView.setDrawType(drawType);
            }
        }
    }

    /**
     * 获取当前区域高度级别
     *
     * @return 高度级别
     */
    private int getCurrentHeightLevel(MyHandWritingView handWritingView) {
        if (null != handWritingView) {
            if (handWritingView.getmHeight() <= mDefHeight + 10) {
                return LEVEL_ONE;
            } else if (handWritingView.getmHeight() <= 2 * mDefHeight + 10) {
                return LEVEL_TWO;
            } else {
                return LEVEL_THREE;
            }
        }
        return LEVEL_ONE;
    }


    private ZuotiHandScrollView scrollView;

    /**
     * 设置WebView自适应屏幕
     */
    public void initWebView() {
        scrollView = findViewById(R.id.scroller);
        mWebView = new WebView(this);
        mHandWritingView.addView(mWebView, 0);
        mHandWritingView.setActionDownView(mWebView);
        WebSettings settings = mWebView.getSettings();

        //settings.setUseWideViewPort(true);//调整到适合webview的大小，不过尽量不要用，有些手机有问题
        settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
        mWebView.setVerticalScrollBarEnabled(false);//不能垂直滑动
        mWebView.setHorizontalScrollBarEnabled(false);//不能水平滑动
        settings.setTextSize(WebSettings.TextSize.LARGEST);//通过设置WebSettings，改变HTML中文字的大小
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        //设置WebView属性，能够执行Javascript脚本
        mWebView.getSettings().setJavaScriptEnabled(true);//设置js可用
        mWebView.addJavascriptInterface(new Mobile(), "mobile");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                String js = "javascript:mobile.onGetWebContentHeight()";
                view.loadUrl(js);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Log.e("jc", cm.
                        message()
                        + " -- From line "
                        + cm.
                        lineNumber()
                        + " of "
                        + cm.
                        sourceId());
                return true;
            }
        });
//        mWebView.addJavascriptInterface(new AndroidJavaScript(getApplication()), "android");//设置js接口
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局


/******  22222222  ***********************************************************************/
//        data = "</Div><head><style>img{ width:100% !important;}</style></head>"+data;//给图片设置一个样式，宽满屏
/******  2222222222  ***********************************************************************/

        mWebView.loadDataWithBaseURL(null, dataStr, "text/html", "utf-8", null);
    }

    private Handler mHandler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Toast.makeText(HandWritingActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
        }
    };

    private class Mobile {
        @JavascriptInterface
        public void onGetWebContentHeight() {
            //重新调整webview高度
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.measure(0, 0);
                    int measuredHeight = mWebView.getMeasuredHeight();
                    Log.e("jc", "measuredHeight=" + measuredHeight);
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mHandWritingView.getLayoutParams();
                    layoutParams.height = measuredHeight;
                    mHandWritingView.setLayoutParams(layoutParams);
                }
            });

        }

        @JavascriptInterface
        public void returnAndroid(String name) {//从网页跳回到APP，这个方法已经在上面的HTML中写上了
            if (name.isEmpty() || name.equals("")) {
                return;
            }
            Toast.makeText(getApplication(), name, Toast.LENGTH_SHORT).show();
            //这里写你的操作///////////////////////
            //MainActivity就是一个空页面，不影响
//            Intent intent = new Intent(WebDataActivity.this, MainActivity.class);
//            intent.putExtra("name",name);
//            startActivity(intent);
        }

        @JavascriptInterface
        public void testToast(String name) {
            if (TextUtils.isEmpty(name)) {
                return;
            }
            mHandler.sendMessage(mHandler.obtainMessage(1, name));
        }

    }


}
